import 'package:flutter/material.dart';

///
/// 可删除标签
///
class QDeleteTag extends StatelessWidget {
  final String title;
  final double fontSize;
  final Color titleColor;
  final bool showDeleteButton;
  final Color buttonColor;
  final Function? onTap;

  const QDeleteTag({
    Key? key,
    required this.title,
    this.fontSize = 14,
    this.titleColor = Colors.black,
    this.buttonColor = Colors.black,
    this.showDeleteButton = true,
    this.onTap,
  }) : super(key: key);

  /// 根据文本计算 Size
  Size getTextSize(String text, TextStyle style) {
    TextPainter painter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
      maxLines: 1,
      ellipsis: '...',
    );
    painter.layout();
    return painter.size;
  }

  @override
  Widget build(BuildContext context) {
    Size size = getTextSize(
        title,
        TextStyle(
          fontSize: fontSize,
          color: titleColor,
        ));
    double width = size.width + 10 * 2 + (showDeleteButton ? 24 : 0);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      width: width,
      decoration: BoxDecoration(
          color: Colors.black26.withOpacity(.1),
          borderRadius: BorderRadius.circular(4)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Text(
              title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: fontSize,
                color: titleColor,
              ),
            ),
          ),
          showDeleteButton
              ? GestureDetector(
                  onTap: () {
                    if (onTap != null) {
                      onTap!.call();
                    }
                  },
                  child: Icon(
                    Icons.close,
                    size: 24,
                    color: buttonColor,
                  ),
                )
              : Container()
        ],
      ),
    );
  }
}
